import Taro from '@tarojs/taro';

// 默认配置
const DEFAULT_CONFIG: Taro.request.Option = {
  url: '',
  method: 'GET',
  dataType: 'json',
  header: {
    'Content-Type': 'application/json',
  },
};

// 请求拦截器
const requestInterceptor = (config: Taro.request.Option) => {
  // 示例：添加 token
  const token = Taro.getStorageSync('token');
  const newConfig: any = {};
  if (token) {
    newConfig.header = {
      ...config.header,
      Authorization: `Bearer ${token}`,
    };
  }

  // 可添加 loading
  Taro.showLoading({ title: '请求中...' });
  return newConfig;
};

// 响应拦截器
const responseInterceptor = (response: Taro.request.SuccessCallbackResult<any>) => {
  Taro.hideLoading();

  const { statusCode, data } = response;

  if (statusCode >= 200 && statusCode < 300) {
    return data;
  }
  // 可统一处理错误
  Taro.showToast({
    title: `请求失败：${data?.message || statusCode}`,
    icon: 'none',
  });
  throw new Error(`HTTP Error: ${statusCode}`);
};

// 错误处理
const handleError = (error: any) => {
  Taro.hideLoading();
  Taro.showToast({
    title: '网络异常，请检查网络',
    icon: 'none',
  });
  console.error('Request Error:', error);
  return Promise.reject(error);
};

/**
 * 通用请求方法
 */
export function request<T = any>(options: Taro.request.Option): Promise<T> {
  // 合并默认配置
  const config = { ...DEFAULT_CONFIG, ...options };

  // 请求拦截
  const interceptedConfig = requestInterceptor(config);

  return Taro.request(interceptedConfig).then(responseInterceptor).catch(handleError);
}

/**
 * 便捷方法封装
 */
export const get = <T = any>(
  url: string,
  data?: any,
  options?: Omit<Taro.request.Option, 'url' | 'data' | 'method'>
) => request<T>({ url, data, method: 'GET', ...options });

export const post = <T = any>(
  url: string,
  data?: any,
  options?: Omit<Taro.request.Option, 'url' | 'data' | 'method'>
) => request<T>({ url, data, method: 'POST', ...options });

export const put = <T = any>(
  url: string,
  data?: any,
  options?: Omit<Taro.request.Option, 'url' | 'data' | 'method'>
) => request<T>({ url, data, method: 'PUT', ...options });

export const del = <T = any>(
  url: string,
  data?: any,
  options?: Omit<Taro.request.Option, 'url' | 'data' | 'method'>
) => request<T>({ url, data, method: 'DELETE', ...options });
